<template>
  <header>
    <div class="search-return" @click="goBack">
      <i class="iconfont icon-fanhui" ></i>
    </div>
    <div class="search-main">
      <i class="iconfont icon-Magnifier"></i>
      <form action="" onsubmit="return false" @keyup.enter="goSearchList">
          <input type="text" placeholder="搜索你喜欢的产品" v-model="searchVal" autofocus>
      </form>
    </div>
    <div class="search-btn" @click="goSearch">搜索</div>
  </header>
</template>

<script>
  export default {
    data(){
      return{
        searchVal:this.$route.query.key || '',
        searchArr:[]
      }
    },
    methods:{
      // 跳转搜索页
      goSearch(){
        // 如果搜索内容相等，就禁止搜索
        if(this.$route.query.key==this.searchVal) return 
        // 跳转搜索页
        if(!this.searchVal.trim()) return
        this.$router.push({
          name:'list',
          query:{
            key:this.searchVal
          }
          })
      },
      // 返回上一页
      goBack(){
        this.$router.back()
      },
      // 输入框搜索
      goSearchList(){
        // 如果搜索内容相等，就禁止搜索
        if(this.$route.query.key==this.searchVal) return 

        // 判断输入框是否有数据
        if(!this.searchVal.trim()) return
        // 判断本地存储是否有搜索记录
        if(localStorage.getItem('searchList')){
          // 如果有
          this.searchArr=JSON.parse(localStorage.getItem('searchList') )
        }else{
          //没有
          localStorage.setItem('searchList',[])
        }
        // 增加数据
        this.searchArr.unshift(this.searchVal)
        // ES6去重
        let arr=new Set(this.searchArr)
        // 给本地存储赋值
        localStorage.setItem('searchList',JSON.stringify(Array.from(arr)))
        // console.log(this.searchArr)

        // 跳转搜索列表页
        this.$router.push({
          name:'list',
          query:{
            key:this.searchVal
          }
          })
      },
    }
  }
</script>

<style lang="scss" scoped>
header{
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 100%;
	height: 1.173333rem;
	color:#fff;
	background-color: #b0352f;
}
.search-return,.search-btn{
  padding:0 0.266666rem;
}
.search-return i{
  font-size:0.746666rem;
}
.search-main{
  display:flex;
  align-items: center;
  width:6.933333rem;
  height:0.8rem;
  border-radius:12px;
  background-color: #ffffff;
  input{
    font-size:0.35rem;
    color:black;
  }
}
.search-main i{
  color:#666;
  padding: 0 0.266666rem;
}
.search-main form{
  display: flex;
  justify-content: center;
  align-items: center;
}
.search-main form input{
  width:100%;
}
.search-btn{
  font-size:0.426666rem;
}
</style>